import { App, Plugin } from "vue";

/** 监听元素大小 */
export function onResize(el: HTMLElement, callback: (ev: Event) => any) {
  const hasobject = el.querySelector("object");
  if (hasobject) {
    return;
  }
  const objEl = document.createElement("object");
  objEl.type = "text/html";
  objEl.data = "about:blank";
  objEl.setAttribute("style", `
      display: block;
      position: absolute;
      top: 0;
      left: 0;
      height: 100%;
      width: 100%;
      overflow: hidden;
      opacity: 0;
      pointer-events: none;
      z-index: -1;
  `);
  objEl.onload = (evt) => {
    objEl.contentDocument.defaultView.addEventListener("resize", (ev) => {
      callback(ev);
    });
    callback(evt);
  };
  el.appendChild(objEl);
}

/** 监听插件 */
export default <Plugin<any[]>>{
  install: function (app: App) {
    // 全局指令
    app.directive("resize", (el, binding) => {
      if (typeof binding.value !== "function") {
        throw new Error("v-resize 绑定值必须为 function");
      }
      onResize(el, binding.value);
    });
    // 方法
    app.config.globalProperties.$onResize = onResize;
  }
}

declare module "@vue/runtime-core" {
  interface ComponentCustomProperties {
    $onResize: typeof onResize;
  }
}
